﻿using HslCommunication.Profinet.Melsec;
using HslCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HslCommunication.Core.Pipe;
using System.Windows.Input;

namespace S7Project_One.Base
{

    public class MelsecMC
    {
        MelsecMcNet? Mc;
        public Dictionary<string, MelsecMcNet> McDectionary = new Dictionary<string, MelsecMcNet>();

        public bool CreateConnectMC(string ip, int[] port)
        {
            // 实例化对象，指定PLC的ip地址和端口号
            Mc = new MelsecMcNet(ip, port[0]);
            // 如果网络不太理想，配置了两个端口，一个有问题，立即切换另一个的话，可以配置如下的代码
            (Mc.CommunicationPipe as PipeTcpNet)!.SetMultiPorts(port);
            // 连接对象
            OperateResult connect = Mc.ConnectServer();
            if (!connect.IsSuccess)
            {
                Console.WriteLine(ip +" connect failed:" + connect.Message);
                return false;
            }
            McDectionary.Add(ip, Mc);
            return true;
        }
        // 获取某个连接对象
        public MelsecMcNet? GetMc(string key)
        {
            return McDectionary.TryGetValue(key, out var value) ? value : null;
        }
        // 关闭连接
        public void CloseMC(string ip)
        {
            if (McDectionary.ContainsKey(ip))
            {
                McDectionary[ip].ConnectClose();
                McDectionary.Remove(ip);
            }
        }
        // 关闭所有连接
        public void CloseAllMC()
        {
            foreach (var item in McDectionary)
            {
                item.Value.ConnectClose();
            }
            McDectionary.Clear();
        }


    }
}
